import axios from "axios";
import config from "./config";
import { typeOf } from "@libs/tools";
// 取消重复请求

function equal(config) {
  return `${config.url}&request_type=${config.method}
  &params=${JSON.stringify(config.data)}&query=${JSON.stringify(
    config.params
  )}`;
}

const pendingList = [];
// 取消重复请求
function removePending(config) {
  for (const p in pendingList) {
    const item = p;
    const pendingObj = pendingList[p];
    // 当前请求在数组中存在时执行函数体
    if (pendingObj.url === equal(config)) {
      // 执行取消操作
      pendingObj.cancel("canceled");
      // 从数组中移除记录
      pendingList.splice(item, 1);
    }
  }
}

//取消请求
function cancelToken(config) {
  config.cancelToken = new axios.CancelToken((c) => {
    pendingList.push({
      url: equal(config),
      cancel: c,
    });
  });
}

//请求拦截函数
function requestFunc(config, cancel) {
  if (cancel) {
    removePending(config);
    cancelToken(config);
  }
  return config;
}

//响应拦截函数
function responseFunc(res, cancel) {
  cancel && removePending(res.config);
  return Promise.resolve(res);
}

function reject(error) {
  return Promise.reject(error);
}

// 返回状态判断(添加响应拦截器)
function createIstance(baseConfig) {
  return function(conf, interceptors, cancel = baseConfig.cancel) {
    interceptors = Object.assign({}, baseConfig.interceptors, interceptors);
    //默认对请求和响应进行拦截
    conf = conf || {};
    const Instance = axios.create(Object.assign({}, config, conf));

    if (typeOf(interceptors) !== "object") return;
    // 添加请求拦截器
    if (interceptors.request === true) {
      //默认请求拦截
      Instance.interceptors.request.use(function(config) {
        return requestFunc(config, cancel);
      }, reject);
    }
    if (typeOf(interceptors.request) === "function") {
      //支持请求拦截自定义
      Instance.interceptors.request.use(async function(config) {
        if (cancel) {
          removePending(config);
          cancelToken(config);
        }
        return await interceptors.request(config);
      }, reject);
    }

    // 添加响应拦截器
    if (interceptors.response === true) {
      //默认响应拦截
      Instance.interceptors.response.use(function(res) {
        return responseFunc(res, cancel);
      }, reject);
    }
    if (typeOf(interceptors.response) === "function") {
      //支持响应拦截自定义
      Instance.interceptors.response.use(function(res) {
        if (cancel) removePending(res.config);
        return interceptors.response(res);
      }, reject);
    }

    return Instance;
  };
}

export default createIstance({
  interceptors: { request: true, response: true }, //开启默认请求响应拦截器，传入函数自定义拦截
  cancel: true, //是否取消重复请求
});
